package com.harmontronics.hanma.paas.paas.domain.app.entity;

import cn.hutool.core.lang.Tuple;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.harmontronics.hanma.paas.paas.consts.BaseI18nKeyEnum;
import com.harmontronics.hanma.paas.paas.exception.ErrorKeyException;
import lombok.Data;
import org.springframework.data.util.Pair;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

/**
 * 第三方服务配置信息
 *
 * @author paas-generator
 * @email paas-generator@harmontronics.com
 * @date 2021-05-17 11:31:06
 */
@Data
public class HttpServiceSetting {

    /**
     * 三方服务ID
     */
    private Long httpServiceId;
    /**
     * 环境
     */
    private String env;
    /**
     * 配置信息
     */
    private String json;

    private String serverUrl;

    private String tokenUrl;

    private String tokenPath;

    private Long tokenExpire;


    public List<Map<String, String>> paramJson2List() {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(this.json, new TypeReference<List<Map<String, String>>>() {
            });
        } catch (JsonProcessingException ex) {
            throw new ErrorKeyException(BaseI18nKeyEnum.REQUEST_PARAM_ERROR);
        }
    }

    public Tuple getMosParamAndCheck() {
        String appIdStr = null;
        String appSecretStr = null;
        String token = null;
        for (Map<String, String> paramMap : paramJson2List()) {
            String name = paramMap.get("name");
            String value = paramMap.get("value");
            if ("appId".equals(name)) {
                appIdStr = value;
            } else if ("appSecret".equals(name)) {
                appSecretStr = value;
            } else if ("token".equals(name)) {
                token = value;
            }
        }
        if (!StringUtils.hasLength(appIdStr) || !StringUtils.hasLength(appSecretStr)) {
            throw new ErrorKeyException(BaseI18nKeyEnum.REQUEST_PARAM_ERROR);
        }
        return new Tuple(appIdStr,appSecretStr,token);
    }

}
